package com.zt.dev.standardManage.controller;

import com.zt.dev.commons.ServerResponse;
import com.zt.dev.standardManage.entity.enmu.CategoryEnum;
import com.zt.dev.standardManage.entity.vo.Standards;
import com.zt.dev.standardManage.service.StandardService;
import com.zt.dev.standardManage.utils.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/standardManage")
public class StandardsController {

    @Autowired
    private StandardService standardService;

    /**
     * 添加评估准则
     * @param standards
     * @return
     */
    @RequestMapping("/insertStandard")
    @ResponseBody
    public ServerResponse insertStandard(Standards standards){
        if(standards != null){
            int result = standardService.insertStandard(standards);
            if(result > 0){
                return ServerResponse.createBySuccessMessage("添加成功");
            }else{
                return ServerResponse.createByErrorMessage("添加失败");
            }
        }
        return ServerResponse.createByErrorMessage("参数为空");
    }

    /**
     * 分页获取准则列表
     * @return
     */
    @RequestMapping("/getStandardPage")
    @ResponseBody
    public ServerResponse getStandardPage(@RequestParam(value = "currentPage", defaultValue = "1", required = true) int currentPage, int pageSize,String standardName){
        PageBean<Standards> pageBean = standardService.getAllStandard(currentPage, pageSize,standardName);
       /* if (!CollectionUtils.isEmpty(pageBean.getLists())) {
            return ServerResponse.createBySuccess(pageBean);
        }
        return ServerResponse.createByErrorMessage("数据为空");*/
        return ServerResponse.createBySuccess(pageBean);
    }

    /**
     * 删除评估准则
     * @param ids
     * @return
     */
    @RequestMapping("/deleteStandard")
    @ResponseBody
    public ServerResponse deleteStandard(Integer[] ids){
        if(ids.length > 0){
            int result = standardService.deleteStandard(ids);
            if(result > 0){
                return ServerResponse.createBySuccessMessage("删除成功");
            }else{
                return ServerResponse.createByErrorMessage("删除失败");
            }
        }
        return ServerResponse.createByErrorMessage("参数为空");
    }

    /**
     * 修改评估准则
     * @param standards
     * @return
     */
    @RequestMapping("/updateStandard")
    @ResponseBody
    public ServerResponse updateStandard(Standards standards){
        if(standards != null){
            int result = standardService.updateStandardById(standards);
            if(result > 0){
                return ServerResponse.createBySuccessMessage("更新成功");
            }else{
                return ServerResponse.createByErrorMessage("更新失败");
            }
        }
        return ServerResponse.createByErrorMessage("参数为空");
    }

    /**
     * 根据名称查询
     * @param standardName
     * @return
     */
    @RequestMapping("/getStandardByName")
    @ResponseBody
    public ServerResponse getStandardByName(String standardName){
        if(standardName != null){
            List<Standards> standardsList = standardService.getStandardByName(standardName);
            if(standardsList != null){
                return ServerResponse.createBySuccess(standardsList);
            }else{
                return ServerResponse.createByErrorMessage("查询为空");
            }
        }
        return ServerResponse.createByErrorMessage("参数为空");
    }

    /**
     * 通过id查询准则
     * @param id
     * @return
     */
    @RequestMapping("/getStandardById")
    @ResponseBody
    public ServerResponse getStandardById(Integer id){
        if(id != null){
            Standards standards = standardService.getStandardById(id);
            if(standards != null){
                return ServerResponse.createBySuccess(standards);
            }else{
                return ServerResponse.createByErrorMessage("查询为空");
            }
        }
        return ServerResponse.createByErrorMessage("参数为空");
    }

    /**
     * 导出Excel
     * @param response
     * @throws Exception
     */
    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response)throws Exception{
        String fileName = "评估准则表" + ".xls";
        List<Standards> standardsList = standardService.getStandardList();
        //对准则类别进行处理
        for(Standards standards:standardsList){
            String category = CategoryEnum.getType(standards.getCategoryNode());
            standards.setCategory(category);
        }
        String[] title1 = new String[]{"序号,1,2"};
        String[] title2 = new String[]{"评估准则名称","评估对象", "准则内容", "评估方法", "准则类别","创建人", "创建时间"};
        String[] column = new String[]{"standardName","target", "context", "method","category", "creater", "createTime"};
        HSSFWorkbook wb = new ExcelUtil().getHSSFWorkbook(fileName,title1,title2,standardsList,column);
        fileName = new String(fileName.getBytes(),"ISO8859-1");
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        response.addHeader("Pargam","no-cache");
        response.addHeader("Cache-Control","no-cache");
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }

    /**
     * 导出XML文件
     * @param response
     * @throws IOException
     */
    @RequestMapping("/exportXml")
    public void exportXml(HttpServletResponse response) throws IOException {
        String currentTime = DateUtil.getStringDateYmd();
        String fileName = "评估准则表" + currentTime + ".xml";
        List<Standards> standardsList = standardService.getStandardList();
        XMLWriter writer = new Dom4jXML().createXml(fileName,standardsList);
        fileName = new String(fileName.getBytes(),"UTF-8");
        System.out.println(fileName);
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(fileName));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes("utf-8"),"ISO8859-1"));
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }

    /**
     * 导出word文件
     * @param response
     */
    @RequestMapping("/exportWord")
    public void exportWord(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = "评估准则表" + ".doc";
        String ftlName = "template/wordModel.ftl";
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Map<String,String>> tableList = new ArrayList<>();
        List<Standards> standardsList = standardService.getStandardList();
        for(Standards standards : standardsList){
            Map<String,String> map = new HashMap<>();
            map.put("standardName",standards.getStandardName());
            map.put("target",standards.getTarget());
            map.put("context",standards.getContext());
            map.put("method",standards.getMethod());
            map.put("category",CategoryEnum.getType(standards.getCategoryNode()));
            map.put("creater",standards.getCreater());
            map.put("createTime",standards.getCreateTime());
            tableList.add(map);
        }
        dataMap.put("tableList",tableList);
        new WordExport().wordUlit(fileName,ftlName,dataMap,response,request);
    }

    /**
     * 获取全部类别
     * @return
     */
    @RequestMapping("/getAllType")
    @ResponseBody
    public ServerResponse getAllType(){
        List<String> categoryList = standardService.getAllType();
        if(!categoryList.isEmpty()){
            return ServerResponse.createBySuccess(categoryList);
        }
        return ServerResponse.createByErrorMessage("查询为空");
    }


    /**
     * 统计当前月各类别量
     * @return
     */
    @RequestMapping("/getStandardByMon")
    @ResponseBody
    public ServerResponse getStandardByMon(String createTime){
        Map<String,Object> resultMap = standardService.getStandardByMon(createTime);
        if(resultMap != null){
            return ServerResponse.createBySuccess(resultMap);
        }
        return ServerResponse.createByErrorMessage("查询为空");
    }

    /**
     * 统计当月准则、模板所占量
     * @return
     */
    @RequestMapping("/getDataByType")
    @ResponseBody
    public ServerResponse getDataByType(String createTime){
        Map<String,Object> resultMap = standardService.getDataByType(createTime);
        if(resultMap != null){
            return ServerResponse.createBySuccess(resultMap);
        }
        return ServerResponse.createByErrorMessage("查询为空");
    }

    /**
     * 统计当月准则、模板量,柱状图
     * @return
     */
    @RequestMapping("/getData")
    @ResponseBody
    public ServerResponse getData(String createTime){
        Map<String,Object> resultMap = standardService.getData(createTime);
        if(resultMap != null){
            return ServerResponse.createBySuccess(resultMap);
        }
        return ServerResponse.createByErrorMessage("查询为空");
    }

    /**
     * 折线图
     * @return
     */
    @RequestMapping("/getDataLine")
    @ResponseBody
    public ServerResponse getDataLine(String createTime){
        Map<String,Object> resultMap = standardService.getDataLine(createTime);
        if(resultMap != null){
            return ServerResponse.createBySuccess(resultMap);
        }
        return ServerResponse.createByErrorMessage("查询为空");
    }

    /**
     * 展示页面折线图
     * @return
     */
    @RequestMapping("/getDataLast")
    @ResponseBody
    public ServerResponse getDataLast(String createTime){
        Map<String,Object> resultMap = standardService.getDataLast(createTime);
        if(resultMap != null){
            return ServerResponse.createBySuccess(resultMap);
        }
        return ServerResponse.createByErrorMessage("查询为空");
    }
}
